package com.efeichong.dynamic;

import org.springframework.aop.Advisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManagerFactory;

/**
 * @author lxk
 * @date 2022/8/28
 * @description 动态数据源自动配置
 */
@Import({DynamicDataSourceRegister.class})
@Conditional(DynamicDataSourceCondition.class)
@Configuration
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public class DynamicDataSourceConfiguration {

    @Bean
    public Advisor dynamicDatasourceAnnotationAdvisor() {
        DynamicDataSourceAnnotationInterceptor interceptor = new DynamicDataSourceAnnotationInterceptor();
        DynamicDataSourceAnnotationAdvisor advisor = new DynamicDataSourceAnnotationAdvisor(interceptor, DS.class);
        advisor.setOrder(-1);
        return advisor;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory, DynamicDataSource dynamicDataSource) {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(entityManagerFactory);
        jpaTransactionManager.setDataSource(dynamicDataSource);
        return jpaTransactionManager;
    }
}
